package com.lizicloud.user.userdelete.service;

import com.lizicloud.application.dto.ApiResponse;
import com.lizicloud.domain.model.User;
import com.lizicloud.infrastructure.persistence.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户删除服务类 - 实现逻辑删除
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDeleteService {
    
    private final UserMapper userMapper;
    
    /**
     * 逻辑删除用户
     */
    @Transactional
    public ApiResponse<Void> logicalDeleteUser(Long userId) {
        try {
            User user = userMapper.selectById(userId);
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            // 检查用户是否已被删除
            if (user.getIsDelete() != null && user.getIsDelete() == 1) {
                return ApiResponse.error("用户已被删除");
            }
            
            // 执行逻辑删除 - 使用updateWrapper确保正确更新isDelete字段
            com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<User> updateWrapper = new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getId, userId)
                        .set(User::getIsDelete, 1)
                        .set(User::getUpdatedTime, LocalDateTime.now());
            
            int updateCount = userMapper.update(null, updateWrapper);
            if (updateCount == 0) {
                return ApiResponse.error("删除用户失败");
            }
            
            log.info("逻辑删除用户成功，用户ID: {}, 用户名: {}", userId, user.getUsername());
            return ApiResponse.success(null);
            
        } catch (Exception e) {
            log.error("逻辑删除用户失败，用户ID: {}", userId, e);
            return ApiResponse.error("删除用户失败");
        }
    }
    
    /**
     * 批量逻辑删除用户
     */
    @Transactional
    public ApiResponse<Void> batchLogicalDeleteUsers(List<Long> userIds) {
        try {
            if (userIds == null || userIds.isEmpty()) {
                return ApiResponse.error("用户ID列表不能为空");
            }
            
            // 查询要删除的用户
            List<User> usersToDelete = userMapper.selectBatchIds(userIds);
            if (usersToDelete.isEmpty()) {
                return ApiResponse.error("没有找到要删除的用户");
            }
            
            // 分离已删除和未删除的用户ID
            List<Long> validUserIds = new java.util.ArrayList<>();
            int skipCount = 0;
            
            for (User user : usersToDelete) {
                if (user.getIsDelete() != null && user.getIsDelete() == 1) {
                    skipCount++;
                    log.warn("用户已被删除，跳过，用户ID: {}, 用户名: {}", user.getId(), user.getUsername());
                } else {
                    validUserIds.add(user.getId());
                }
            }
            
            if (validUserIds.isEmpty()) {
                return ApiResponse.error("批量删除用户失败，所有用户已被删除");
            }
            
            // 使用updateWrapper批量更新isDelete字段
            com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<User> updateWrapper = new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<>();
            updateWrapper.in(User::getId, validUserIds)
                        .set(User::getIsDelete, 1)
                        .set(User::getUpdatedTime, LocalDateTime.now());
            
            int updateCount = userMapper.update(null, updateWrapper);
            
            if (updateCount == 0) {
                return ApiResponse.error("批量删除用户失败");
            }
            
            String message = String.format("批量删除完成，成功删除 %d 个用户，跳过 %d 个已删除用户", 
                    updateCount, skipCount);
            log.info("批量逻辑删除用户完成，成功: {}, 跳过: {}, 用户IDs: {}", 
                    updateCount, skipCount, userIds);
            
            return ApiResponse.success(null);
            
        } catch (Exception e) {
            log.error("批量逻辑删除用户失败，用户IDs: {}", userIds, e);
            return ApiResponse.error("批量删除用户失败");
        }
    }
    
    /**
     * 彻底删除用户（物理删除，慎用）
     */
    @Transactional
    public ApiResponse<Void> physicalDeleteUser(Long userId) {
        try {
            User user = userMapper.selectById(userId);
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            int deleteCount = userMapper.deleteById(userId);
            if (deleteCount == 0) {
                return ApiResponse.error("删除用户失败");
            }
            
            log.warn("物理删除用户，用户ID: {}, 用户名: {}", userId, user.getUsername());
            return ApiResponse.success(null);
            
        } catch (Exception e) {
            log.error("物理删除用户失败，用户ID: {}", userId, e);
            return ApiResponse.error("删除用户失败");
        }
    }
    
    /**
     * 恢复已删除的用户
     */
    @Transactional
    public ApiResponse<Void> restoreUser(Long userId) {
        try {
            User user = userMapper.selectById(userId);
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            if (user.getIsDelete() == null || user.getIsDelete() == 0) {
                return ApiResponse.error("用户未被删除，无需恢复");
            }
            
            // 恢复用户 - 使用updateWrapper确保正确更新isDelete字段
            com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<User> updateWrapper = new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getId, userId)
                        .set(User::getIsDelete, 0)
                        .set(User::getUpdatedTime, LocalDateTime.now());
            
            int updateCount = userMapper.update(null, updateWrapper);
            if (updateCount == 0) {
                return ApiResponse.error("恢复用户失败");
            }
            
            log.info("恢复用户成功，用户ID: {}, 用户名: {}", userId, user.getUsername());
            return ApiResponse.success(null);
            
        } catch (Exception e) {
            log.error("恢复用户失败，用户ID: {}", userId, e);
            return ApiResponse.error("恢复用户失败");
        }
    }
}